package sg.edu.nus.iss.billing.gui;
/**
 * @author sammil
 *
 */
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;

import sg.edu.nus.iss.billing.controller.BillGenerator;
import sg.edu.nus.iss.billing.controller.CustomerController;
import sg.edu.nus.iss.billing.entity.Account;
import sg.edu.nus.iss.billing.entity.Customer;
import sg.edu.nus.iss.billing.entity.RecordState;
import sg.edu.nus.iss.billing.exception.ValidationException;
import sg.edu.nus.iss.billing.gui.component.ErrorDialog;
import sg.edu.nus.iss.billing.gui.component.ValidateJTextField;
import sg.edu.nus.iss.billing.localization.MessageKeyManager;
import sg.edu.nus.iss.billing.validation.ValidationRule;

public class ViewBillPanel extends DefaultFunctionPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1257462897091593886L;
	
	private ValidateJTextField accountNoTxt;
	private ValidateJTextField nricTxt;
	private ValidateJTextField yearText;
	private BillGenerator billGenerator;
	private CustomerController customerController;
	private JComboBox monthCombo;
	private JPanel bottomPanel;
	java.util.Calendar calendar = java.util.Calendar.getInstance();
	java.util.Calendar selectedCalendar = Calendar.getInstance();
	Calendar billingCalendar = Calendar.getInstance();
	String billingCycle = null;
	private Date selectedDate;
	String fileSeparator = System.getProperty("file.separator");
	private static String generatedBillsFolder = "bills";
	
	/**
	 * Create the panel.
	 */
	public ViewBillPanel() {
		
		super.init("");
		this.billGenerator = new BillGenerator(); 
		this.customerController = new CustomerController();
		billingCycle = MessageKeyManager.getMessage("bill.billingCycle");
		billingCalendar.set(Calendar.DATE, Integer.parseInt(billingCycle));
	}

	
	private void clearAllFields() {
		this.accountNoTxt.setText("");
		this.nricTxt.setText("");
		yearText.setText(getCurrentYear());
		if ( calendar.get(Calendar.DATE) > billingCalendar.get(Calendar.DATE)){
			this.monthCombo.setSelectedIndex(getCurrentMonth() );
		}else {
			this.monthCombo.setSelectedIndex(getCurrentMonth()  -1 );
		}
	}

	
	@Override
	public JPanel createTopPanel() {
			return null;
	 	
	}

	@Override
	public JPanel createBottomPanel() {
		this.bottomPanel = new JPanel(new BorderLayout());
		
		this.bottomPanel.setBorder(new TitledBorder(null, MessageKeyManager
				.getMessage("bill.label.billdetails"), TitledBorder.LEADING,
				TitledBorder.TOP, null, null));

		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0, 0};
		gridBagLayout.rowHeights = new int[]{0, 0};
		gridBagLayout.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};

		JPanel contentPanel = new JPanel(gridBagLayout);
		this.bottomPanel.add(contentPanel, BorderLayout.NORTH);

		this.monthCombo = new JComboBox();
		String monthsList[] = new String[12];
		for(int i = 0; i <  monthsList.length;i++){
			monthsList[i] = MessageKeyManager.getMessage("bill.list.month.option"+(i+1));
		}
		this.monthCombo.setModel(new DefaultComboBoxModel(monthsList));
		
		this.accountNoTxt = new ValidateJTextField(MessageKeyManager.getMessage("bill.list.account.label"), ValidationRule.NOT_NULL);
		this.nricTxt = new ValidateJTextField(MessageKeyManager.getMessage("bill.list.nric.label"), ValidationRule.NRIC);
		this.yearText = new ValidateJTextField(MessageKeyManager.getMessage("bill.list.year.label"), ValidationRule.NOT_NULL);
		
		String[] labels = new String[] {"bill.list.account.label","bill.list.nric.label", "bill.list.month.label",	"bill.list.year.label"};
		for (int i = 0; i < labels.length; i++) {
			GridBagHelper.addLabel(contentPanel, MessageKeyManager.getMessage(labels[i]), 
					SwingConstants.RIGHT, 0, i, GridBagConstraints.WEST, 0, GridBagHelper.INSETS_LARGE);
		}
		
		
		int x = 0;
		GridBagHelper.addComponent(contentPanel, this.accountNoTxt, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.nricTxt, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.monthCombo, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		GridBagHelper.addComponent(contentPanel, this.yearText, 1, x++, 0, GridBagHelper.INSETS_LARGE);
		

		Customer customer = SessionContext.getCustomer();
		if (customer != null) {
			this.accountNoTxt.setText(customer.getAccountNumber());
		}
		yearText.setText(getCurrentYear());
		if ( calendar.get(Calendar.DATE) > billingCalendar.get(Calendar.DATE)){
			this.monthCombo.setSelectedIndex(getCurrentMonth() );
		}else {
			this.monthCombo.setSelectedIndex(getCurrentMonth()  -1 );
		}
		return this.bottomPanel;
	}
	
	
	
	@Override
	public JPanel createActionButtonsPanel() {
		JPanel buttonPanel = new JPanel();
		FlowLayout thisLayout = new FlowLayout();
		thisLayout.setAlignment(FlowLayout.CENTER);
		buttonPanel.setLayout(thisLayout);
			

		JButton btnNewButton = new JButton(MessageKeyManager.getMessage("bill.button.view"));
		btnNewButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				viewButtonPressed();
			}
		});
		buttonPanel.add(btnNewButton);
		
		
		JButton btnReset = new JButton(MessageKeyManager.getMessage("bill.button.reset"));
		btnReset.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				resetButtonPressed();
			}
		});
		buttonPanel.add(btnReset);
		

		return buttonPanel;
	}
	
	void viewButtonPressed() {	
		try {
			
			String accountNumber = null;
			String nricNumber = null;
			Customer customer = null;
			String htmlString = null;
			
			if(this.accountNoTxt.getText().trim().length() == 0 &&
					this.nricTxt.getText().trim().length() == 0){
				throw new ValidationException(MessageKeyManager.getMessage("bill.err.acctnric.empty"));
			}
			
			if(this.accountNoTxt.getText().trim().length() > 1){
				accountNumber = this.accountNoTxt.getValidatedText();
				customer = customerController.getCustomerByAccount(accountNumber);
			}else if(this.nricTxt.getText().trim().length() > 1){
				nricNumber = this.nricTxt.getValidatedText();
				customer = customerController.getCustomerByNRIC(nricNumber);
				accountNumber = customer.getAccountNumber();
			}
			
			if (RecordState.DELETED.equals(customer.getActive())) {
				JOptionPane.showMessageDialog(null, MessageKeyManager.getMessage("msg.deleteCustomer"), "Deleted Customer", JOptionPane.INFORMATION_MESSAGE);
				return;
			}
			
			if(isBillReady()){
				int billMonth = ( 1 + selectedCalendar.get(Calendar.MONTH));
				int billYear =  selectedCalendar.get(Calendar.YEAR);
				String billMonthStr = ""+ ((billMonth > 9)?billMonth:"0"+billMonth);
				String currentMonthBillFolder = "bills_"+billYear+""+billMonthStr;
				
				if(new File( generatedBillsFolder ).mkdir()){
					System.out.println("Created Folder For " + generatedBillsFolder  );
				}
				System.out.println("Creating Bill for customer:"+ 	accountNumber + " For Month " + billMonthStr);
			
				if(new File( generatedBillsFolder + fileSeparator + currentMonthBillFolder).mkdir()){
					System.out.println("Created Folder For " + generatedBillsFolder + fileSeparator + currentMonthBillFolder );
				}
				File billFile = new File( generatedBillsFolder + fileSeparator + 
					      currentMonthBillFolder + fileSeparator + accountNumber + ".html");
				Account acctObj = customer.getAccount();
				htmlString = billGenerator.generateBill(selectedCalendar, acctObj, billFile);
				new GeneratedBillFrame("Generated Bill For Acc No:"+ accountNumber ,customer,htmlString);
			
			}else{
				throw new ValidationException(MessageKeyManager.getMessage("bill.notReadyMsg"));
			}
		} catch (ValidationException ve) {
			ErrorDialog.showValidationErrorMessageDialog(ve);
		
		} catch (Exception ex) {
			ErrorDialog.showUnhandledErrorMessageDialog(ex);
		}
	}
	
	

	void resetButtonPressed() {				
		clearAllFields();
	}
	
	public String getCurrentYear(){
		return ""+calendar.get(java.util.Calendar.YEAR);
	}
	public int getCurrentMonth(){
		return calendar.get(java.util.Calendar.MONTH);
	}
	
	public boolean isBillReady(){
		
		
		
				
		
		selectedCalendar.set(Calendar.MONTH, monthCombo.getSelectedIndex());
		selectedCalendar.set(Calendar.YEAR, Integer.parseInt(yearText.getText()));
		selectedDate = selectedCalendar.getTime();
		
		if( selectedCalendar.get(Calendar.YEAR) > calendar.get(Calendar.YEAR)){
				return false;
		} else if ( selectedCalendar.get(Calendar.YEAR) == calendar.get(Calendar.YEAR) &&
					selectedCalendar.get(Calendar.MONTH) > calendar.get(Calendar.MONTH)){
			return false;
		} else if ( selectedCalendar.get(Calendar.YEAR) == calendar.get(Calendar.YEAR) &&
				selectedCalendar.get(Calendar.MONTH) == calendar.get(Calendar.MONTH)){
			
				if ( calendar.get(Calendar.DATE) < billingCalendar.get(Calendar.DATE)){
					return false;
				}
		}
		return true;
		
	}
	
	
	
	public static void main(String [] args) {
		JFrame frame = new JFrame();
		frame.getContentPane().add(new ViewBillPanel());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
}